#--coding:utf-8--
# @Time    : 2022/4/28/028 23:10
# @Author  : hakold
# @File    : register_model.py
# @PROJECT : chatroom_game

import json
import pymongo

def mongo_connect():
    #myclient = pymongo.MongoClient('mongodb+srv://hakold:52Beebee@cluster0.gy1rb.mongodb.net/xiuxian?retryWrites=true&w=majority/')
    myclient = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
    #dblist = myclient.list_database_names()
    # dblist = myclient.database_names() 
    mydb = myclient["qt_game"] #创建数据库
    #collist = mydb.list_collection_names()
    mycol = mydb["player"] #集合
    return mycol

def login(data_dict):  # 登录逻辑
    account = data_dict["account"].strip()
    password = data_dict["password"].strip()
    data = {}
    if account and password: #account、password、nickname均不为空，才走注册验证逻辑
        #code, msg = register_check(account, password, nickname)
        mycol = mongo_connect()
        check_result = checklogin(mycol, account, password)
        if check_result[0]:
            # 登录成功，返回内容
            msg = "登录成功"
            code = "200"
            data['data'] = check_result[1]
        else:
            code = check_result[1][0]
            msg = check_result[1][1]
        
    elif not account:
        code = "506"
        msg = "登录账号不能为空"
    elif not password:
        code = "507"
        msg = "登录密码不能为空"

    data["code"] = code
    data["msg"] = msg
    data["type"] = "login"
    data = json.dumps(data)
    return data

def checklogin(mycol, account, password):
    # 检查账号密码
    check_query = { "account" : account }
    check_doc = list(mycol.find(check_query))
    check_list = []
    for x in check_doc:
        check_list.append(x)
    if len(check_list) > 0:
        del check_list[0]['_id']
        if password == check_list[0]['password']:
            # 密码正确
            return [True, check_list[0]]
        else:
            # 密码错误
            code = "509"
            msg = "登录用户不存在"
            return [False,[code,msg]]
    else:
        # 账号不存在
        code = "508"
        msg = "登录用户不存在"
        return [False,[code,msg]]


# def register_check(account,password,nickname): #注册验证逻辑
#     checkUser = checkUser(account) #通过账号查询用户信息
#     if len(checkUser) > 0: #如果查询到用户信息，表示该账号已经注册
#         data = ("600005","账号【%s】已注册" %account)
#     else:
#         user_db.insertUser(account,password,nickname) #将用户信息插入数据库
#         data = ("000000","账号【%s】注册成功,点击“确定”进入聊天页面" %account)
#     return data
